package com.programs.waw;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AliceResultListView extends Activity implements
		OnItemClickListener, OnClickListener {

	private String ssid;
	private List<AliceData> list;
	private ListView listView;

	@Override
	@SuppressWarnings("unchecked")
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.alice_list);

		Intent intent = getIntent();

		ssid = intent.getStringExtra(getPackageName() + ".ssid");
		list = ((List<AliceData>) intent.getSerializableExtra(getPackageName()
				+ ".listAlice"));

		// ((TextView) findViewById(R.id.ssidText)).append(ssid);
		((TextView) findViewById(R.id.ssidText)).setText(ssid);

		View connectButton = findViewById(R.id.connection_button);
		connectButton.setOnClickListener(this);

		listView = (ListView) findViewById(R.id.resultListView);
		listView.setOnItemClickListener(this);
		listView.setAdapter(new AliceAdapter(this, R.layout.single_element,
				new ArrayList<AliceData>(), ssid.split("-")[1]));

		new BackgroundWorker().execute();

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		AliceData a = (AliceData) listView.getItemAtPosition(position);
		Log.i("Long Click", a.toString());

		ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		clipboard.setText(a.getWpa());
		Toast.makeText(getApplicationContext(),
				"Stringa copiata negli appunti", Toast.LENGTH_LONG).show();

	}

	@SuppressWarnings("unchecked")
	private class BackgroundWorker extends AsyncTask<Void, AliceData, Void> {

		@Override
		protected void onPreExecute() {
			((ArrayAdapter<AliceData>) listView.getAdapter()).clear();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {

			Collections.sort(list);

			for (AliceData a : list) {
				publishProgress(a);
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(AliceData... values) {
			((ArrayAdapter<AliceData>) listView.getAdapter()).add(values[0]);
			super.onProgressUpdate(values);
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.connection_button:

			startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
			break;

		default:
			break;
		}

	}

}
